import { CCBoolean, CCInteger, Prefab, UITransform, _decorator, instantiate } from 'cc';
import { WanderList } from '../Defines';
import ScrollChildItem from './ScrollChildItem';
import ScrollItem from './ScrollItem';

const { ccclass, property } = _decorator;

@ccclass
export default class ScrollMultiItem extends ScrollItem {

    @property(Prefab)
    private pfbChildItem: Prefab = null!;

    @property(CCInteger)
    private childCount = 1;

    @property(CCBoolean)
    private isVertical = true;

    private _cache_$abc: ScrollChildItem[] = [];

    onLoad() {
        const uiTransform = this.node.getComponent(UITransform)!;
        const totalSize = this.isVertical ? uiTransform.width : uiTransform.height;

        let perSize = 0;

        for (let i = 0; i < this.childCount; ++i) {
            let node = instantiate(this.pfbChildItem);
            let comp = node.getComponent(ScrollChildItem)!;
            this._cache_$abc[i] = comp;
            comp.setVisible(false);
            comp.setClickCb((cmd) => {
                this._proxyChildClick(node, i, cmd);
            });
            this.node.addChild(node);

            const nodeUITransform = node.getComponent(UITransform)!;
            if (perSize == 0) {
                perSize = this.isVertical ? nodeUITransform.width : nodeUITransform.height;
            }
        }

        let spaceSize = (totalSize - this.childCount * perSize) / (this.childCount - 1);
        if (this.isVertical) {
            this.node.children.forEach((n, i) => {
                n.setPosition(-totalSize / 2 + perSize / 2 + i * (spaceSize + perSize), 0)
            });
        } else {
            this.node.children.forEach((n, i) => {
                n.setPosition(0, -totalSize / 2 + perSize / 2 + i * (spaceSize + perSize))
            });
        }
    }

    public setData(v: any) {
        let list = v as WanderList.Data[];

        for (let i = 0; i < this.childCount; ++i) {
            let data = list[i];
            let comp = this._cache_$abc[i];
            if (data) {
                comp.setData(data);
                comp.setVisible(true);
            } else {
                comp.setVisible(false);
            }
        }
        super.setData(v);
    }

}